<?php

namespace App\Http\Controllers\API\Admin;

use App\Http\Requests\CreateCategoryRequest;
use App\Http\Requests\UpdateCategoryRequest;
use App\Models\Category;
use App\Models\Goods;
use App\Repositories\CategoryRepository;
use App\Http\Controllers\AppBaseController;
use App\Repositories\PicturesRepository;
use App\ZL\Controllers\ApiBaseController;
use Illuminate\Http\Request;
use Flash;
use Illuminate\Support\Facades\Auth;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

class CategoryAPIAdminController extends ApiBaseController
{
    private $categoryRepository;
    protected $model_name = 'App\Models\Category';
    protected $model_load_array = [
        'goods'
    ];

    public function __construct(CategoryRepository $categoryRepo)
    {
        $this->categoryRepository = $categoryRepo;
    }


    public function authLimit()
    {
        $shop = Auth::guard('admin')->user()->shop;
        $limit = [];
        $limit[] = ['shop_id', $shop->id];
        return $limit;
    }

    public function index(Request $request)
    {
        $model = $this->modelPipeline([
            'modelGetAuthLimit',
            'modelGetSearch',
            'modelGetSort',
        ]);
        $model_data = clone $model;
        $count = $model->count();
        $list = $this->modelPipeline([
            'modelGetPageData',
            'collectionGetLoads',
            'modelByAfterGet',
        ],$model_data);

        return responseZK(1,$list,'',['count'=>$count]);
    }

    public function _after_get($array)
    {
        foreach ($array as &$v) {
            $v->goods_num = $v->goods()->count();
        }
        return $array;
    }

    public function _after_find(&$data)
    {
    }

    /**
     * Display a listing of the Category.
     * GET|HEAD /categories
     *
     * @param Request $request
     * @return Response
     */


    public function beforeStore($id, $request)
    {
        $shop = Auth::guard('admin')->user()->shop;
        $cate = Category::find($id);
        $cate->shop_id = $shop->id;
        $cate->save();
        return responseZK(1,$cate);
    }

    public function beforeUpdate($id, $request)
    {
        $shop = Auth::guard('admin')->user()->shop;
        $cate = Category::find($id);
        $cate->shop_id = $shop->id;
        $cate->save();
        return responseZK(1,$cate);
    }
}
